package office.stock.persistance;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import office.stock.model.BaseEntity;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public abstract class AbstractGenericDAO<T extends BaseEntity> implements GenericDAO<T> {

    @PersistenceContext(unitName = "office_stock_jpa_unit")
    protected EntityManager entityManager;

    public abstract Class<T> getEntityClass();

    private final static Log log = LogFactory.getLog(AbstractGenericDAO.class);
    
    @Override
    public T getById(Long id) {
	T result = null;
	if (id > 0) {
	    result = entityManager.find(getEntityClass(), id);
	}
	return result;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<T> getAll() {
	StringBuilder query = new StringBuilder();
	query.append("SELECT e FROM ").append(getEntityClass().getSimpleName()).append(" e");
	return entityManager.createQuery(query.toString()).getResultList();
    }

    @Override
    public void persist(T entity) {
	entityManager.persist(entity);
	log.debug("Stored " + getEntityClass());
    }

    @Override
    public void update(T entity) {
	entityManager.merge(entity);
    }

    @Override
    public T remove(final Long id) {
	log.debug("removing entity " + getEntityClass().getSimpleName() + " with id " + id);
	if (id == null) {
	    return null;
	}
	T entity = getById(id);
	if (entity != null) {
	    log.debug("Entity found and will be removed");
	    entityManager.remove(entity);
	} else {
	    log.debug("There is no entity with id " + id);
	}
	return entity;
    }

}
